<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use app\common\model\Card as RechargeCard;
use app\common\model\WebSite;

class Card extends Base
{
    public function index()
    {
        $where                 = [];
        $this->view->card_list = RechargeCard::with('use_user,create_user')->where($where)->order('status desc,create_time desc')->paginate(50);
        $this->view->page      = $this->view->card_list->render();
        return $this->fetch();
    }

    public function create()
    {
        global $_G;
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (empty($post['rule'])) {
                return $this->error('请输入正确的卡密生成规则');
            }
            if (intval($post['numbers']) <= 0) {
                return $this->error('请输入正确的卡密张数');
            }

            $card_id = [];
            for ($i = 0; $i < $post['numbers']; $i++) {
                $card_id[$i] = replace_random_str($post['rule']);
            }
            foreach (RechargeCard::where('card_id', 'in', $card_id)->field('card_id')->select() as $old) {
                $k = array_search($old['card_id'], $card_id);
                unset($card_id[$k]);
            }
            foreach ($card_id as $k => $name) {
                RechargeCard::create([
                    'card_id'       => $name,
                    'create_uid'    => $_G['uid'],
                    'account_times' => $post['account_times'],
                    'valid_time'    => $post['valid_time'] == -1 ? -1 : $post['valid_time'] * 3600,
                    'access_times'  => $post['access_times'] ?: [],
                    'from'          => 'admin_create',
                    'status'        => 1,
                ]);
            }

            return $this->success('本次成功生成' . count($card_id) . '张卡密！', 'admin/card/index');
        }

        $this->view->site_list = WebSite::select();
        return $this->fetch();
    }

    public function export()
    {
        return $this->success('功能开发中..');
    }

    public function delete($card_id = 0)
    {
        if (!$this->request->isAjax()) {
            return $this->error('请求类型错误');
        }
        $card = RechargeCard::where('card_id', '=', $card_id)->find();
        if (empty($card)) {
            return $this->error('指定数据不存在');
        }
        $card->delete();
        return $this->success('充值卡删除成功');
    }
}
